package com.mrt.chatgpt.data.domain.auth.service;

import com.google.common.cache.Cache;
import com.mrt.chatgpt.data.domain.auth.model.entity.AuthStateEntity;
import com.mrt.chatgpt.data.domain.auth.model.valobj.AuthTypeVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author 86135
 * @Date 2024/3/15 18:34
 * @Description
 * @Version 1.0
 * @快捷键 getterANDsetter ALT+Insert
 * @快捷键 Ctrl+/或者Ctrl+Shift+/都可以快速注释
 * @快捷键 Ctrl+D 快速复制代码
 * @“ctrl+r”快捷键,用于当前文件内容替换,指的是在当前打开的文件中替换匹配的字符,只操作一个文件;
 * @ALT+鼠标左键 整列编辑
 * @快捷键提示 ALT+Enter
 * @快捷键 快速写注释：在方法函数上方输入/** 然后回车
 * @快捷键 Ctrl+O，选择重写的方法
 * @快捷键 ALT+INSERT
 */
@Slf4j
@Service
public class AuthService extends AbstractAuthService{

    @Resource
    private Cache<String,String> codeCache;
    @Override
    protected AuthStateEntity checkCode(String code) {
        //获取验证码校验
        String openId = codeCache.getIfPresent(code);
        if(StringUtils.isBlank(openId)){
            log.info("鉴权，用户收入的验证码不存在{}", code);
            return AuthStateEntity.builder()
                    .code(AuthTypeVO.A0001.getCode())
                    .info(AuthTypeVO.A0000.getInfo())
                    .build();
        }
        // 移除缓存Key值
        codeCache.invalidate(openId);
        codeCache.invalidate(code);

        //验证码校验成功
        return AuthStateEntity.builder()
                .code(AuthTypeVO.A0000.getCode())
                .info(AuthTypeVO.A0000.getInfo())
                .openId(openId)
                .build();


    }

    @Override
    public boolean checkToken(String token) {
        return isVerify(token);
    }

    @Override
    public String openid(String token) {
        Claims claims = decode(token);
        return claims.get("openId").toString();
    }
}
